﻿using System.Linq.Expressions;
using System.Reflection;

namespace WenAntdUI.Helps;

public static class ExpressionHelp
{
    public static string GetMemberName<T>(this Expression<Func<T, object>> expr)
    {
        var member = expr?.Body switch
        {
            MemberExpression m => m,
            UnaryExpression { Operand: MemberExpression m } => m,
            _ => null
        } ?? throw new Exception("数据获取失败");
        return member.Member.Name;
    }
    /// <summary>
    /// 获取成员表达式
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="expr"></param>
    /// <returns></returns>
    /// <exception cref="Exception"></exception>
    public static MemberExpression GetMemberExpression<T>(this Expression<Func<T, object>> expr)
    {
        var member = expr?.Body switch
        {
            MemberExpression m => m,
            UnaryExpression { Operand: MemberExpression m } => m,
            _ => null
        } ?? throw new Exception("数据获取失败");
        return member;
    }
    /// <summary>
    /// 获取成员信息
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="expr"></param>
    /// <returns></returns>
    /// <exception cref="Exception"></exception>
    public static MemberInfo GetMemberInfo<T>(this Expression<Func<T, object>> expr)
    {
        var member = expr?.Body switch
        {
            MemberExpression m => m,
            UnaryExpression { Operand: MemberExpression m } => m,
            _ => null
        } ?? throw new Exception("数据获取失败");
        return member.Member;
    }
}
